package com.meituan.catering.management.order.biz.service.impl;

import com.meituan.catering.management.common.model.api.http.UserContextHttpRequest;
import com.meituan.catering.management.common.model.api.thrift.UserContextThriftRequest;
import com.meituan.catering.management.order.api.http.model.request.*;
import com.meituan.catering.management.order.biz.model.CateringOrderBO;
import com.meituan.catering.management.order.biz.model.CateringOrderItemAccessoryBO;
import com.meituan.catering.management.order.biz.model.CateringOrderItemBO;
import com.meituan.catering.management.order.biz.service.CateringOrderBizService;
import com.meituan.catering.management.order.biz.service.CateringOrderQueryService;
import com.meituan.catering.management.order.dao.mapper.CateringOrderItemAccessoryMapper;
import com.meituan.catering.management.order.dao.mapper.CateringOrderItemMapper;
import com.meituan.catering.management.order.dao.mapper.CateringOrderMapper;
import com.meituan.catering.management.order.dao.model.CateringOrderDO;
import com.meituan.catering.management.order.dao.model.CateringOrderItemAccessoryDO;
import com.meituan.catering.management.order.dao.model.CateringOrderItemDO;
import com.meituan.catering.management.order.remote.ProductRemoteService;
import com.meituan.catering.management.order.remote.ShopRemoteService;
import com.meituan.catering.management.order.remote.model.response.ProductDetailRemoteResponse;
import com.meituan.catering.management.order.remote.model.response.ShopDetailRemoteResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CateringOrderBizServiceImpl implements CateringOrderBizService {
    private static ProductDetailRemoteResponse saveObj = null;
    @Resource
    private CateringOrderMapper cateringOrderMapper;
    @Resource
    private CateringOrderItemMapper cateringOrderItemMapper;
    @Resource
    private CateringOrderItemAccessoryMapper cateringOrderItemAccessoryMapper;
    @Resource
    private CateringOrderQueryService cateringOrderQueryService;
    /**
     * 引入门店thrift
     */
    @Resource
    private ShopRemoteService shopRemoteService;
    /**
     * 引入商品thrift
     */
    @Resource
    private ProductRemoteService productRemoteService;

    /**
     * 创建订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CateringOrderBO creationOrder(UserContextHttpRequest userContextHttpRequest, PlaceCateringOrderHttpRequest request) {
        /*
         * 插入订单主表
         */
        CateringOrderDO cateringOrderDO = buildOrderDO(userContextHttpRequest, request);
        UserContextThriftRequest userContextThriftRequest = buildThriftUserContext(userContextHttpRequest);
        ShopDetailRemoteResponse byBusinessNo = shopRemoteService.findByBusinessNo(userContextThriftRequest, request.getShopBusinessNo());
        cateringOrderDO.setShopId(byBusinessNo.getId());
        cateringOrderDO.setShopNameOnPlace(byBusinessNo.getName());
        Integer insert = cateringOrderMapper.insert(cateringOrderDO);
        if (insert > 0) {
            request.getItems().stream().peek(item->{
                CateringOrderItemDO cateringOrderItemDO = buildOrderItemDO(userContextThriftRequest, item, cateringOrderDO.getId());
                cateringOrderItemMapper.insert(cateringOrderItemDO);
                    List<CateringOrderItemAccessoryDO> accessoryDOS = item.getAccessories().stream().map(acc -> {
                        return buildOrderItemAccDO(userContextThriftRequest, acc, cateringOrderItemDO.getId());
                    }).collect(Collectors.toList());
                    if (accessoryDOS.size() > 0) {
                        cateringOrderItemAccessoryMapper.insertAll(accessoryDOS);
                    }
            }).count();
        }else {
            throw new IllegalArgumentException("主订单插入失败");
        }
        /*
         * 查询当前订单详情
         */
        return cateringOrderQueryService.findById(userContextHttpRequest, cateringOrderDO.getId());
    }

    /**
     * 制作订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CateringOrderBO makeOrder(UserContextHttpRequest userContextHttpRequest, Long orderId, PrepareCateringOrderHttpRequest request) {
        /*
         * 修改订单子项 如果订单子项全部更改 则修改订单主表
         */
        CateringOrderBO cater = cateringOrderQueryService.findById(userContextHttpRequest, orderId);

        for (PrepareCateringOrderHttpRequest.Item item : request.getItems()) {
            /*
             * 子项根据 序号 以及主订单id修改其状态
             */
            CateringOrderItemBO itemByOrderId = cateringOrderQueryService.findItemByOrderId(orderId, item.getSeqNo(), userContextHttpRequest.getTenantId());
            if (itemByOrderId != null) {
                if ("PREPARING".equals(String.valueOf(itemByOrderId.getStatus()))) {
                    throw new IllegalArgumentException("序号为" + item.getSeqNo() + "已经为制作状态");
                } else {
                    /*
                     * 制作子订单 以及子订单下面的加料
                     */
                    cateringOrderItemMapper.makeOrder(userContextHttpRequest.getTenantId(), orderId, item.getSeqNo(), item.getVersion());
                    cateringOrderItemAccessoryMapper.makeOrder(userContextHttpRequest.getTenantId(), itemByOrderId.getId());
                }
            }

        }
        List<CateringOrderItemBO> itemsByOrderId = cateringOrderQueryService.findItemsByOrderId(userContextHttpRequest.getTenantId(), orderId);
        long count = itemsByOrderId.stream().filter(item -> "PREPARING".equals(String.valueOf(item.getStatus()))).count();
        /*
         * 只要有一个在制作 则该订单都在制作中
         */
        if (count >= 1L) {
            CateringOrderDO cateringOrderDO = buildOrderDO(userContextHttpRequest, orderId, request.getVersion());
            cateringOrderMapper.makeOrder(cateringOrderDO);
        }

        return cateringOrderQueryService.findById(userContextHttpRequest, orderId);
    }

    /**
     * 订单出餐
     * 只有当子项全部出餐成功  父项才更改状态为已经出餐
     *
     * @param userContextHttpRequest 头部信息 租户号 用户号
     * @param orderId 订单id
     * @param request                CateringOrderBO
     * @return CateringOrderBO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CateringOrderBO produceOrder(UserContextHttpRequest userContextHttpRequest, Long orderId, ProduceCateringOrderHttpRequest request) {
        /*
         * 修改订单子项 如果订单子项全部更改 则修改订单主表
         */
        CateringOrderBO cater = cateringOrderQueryService.findById(userContextHttpRequest, orderId);
        if ("PREPARED".equals(String.valueOf(cater.getStatus()))) {
           throw  new IllegalArgumentException("订单已全部出餐");
        }
        for (ProduceCateringOrderHttpRequest.Item item : request.getItems()) {
            /*
             * 子项根据 序号 以及主订单id修改其状态
             */
            CateringOrderItemBO itemByOrderId = cateringOrderQueryService.findItemByOrderId(orderId, item.getSeqNo(), userContextHttpRequest.getTenantId());
            if (!"PREPARED".equals(String.valueOf(itemByOrderId.getStatus()))) {
                /*
                 * 子项不是出餐状态 修改其子项的加料
                 */
                for (ProduceCateringOrderHttpRequest.Item.Accessory accs : item.getAccessories()) {
                    CateringOrderItemAccessoryBO itemByItemId = cateringOrderQueryService.findItemAccByItemId(itemByOrderId.getId(), accs.getSeqNo(), userContextHttpRequest.getTenantId());
                    if (!"PREPARED".equals(String.valueOf(itemByItemId.getStatus()))) {
                        CateringOrderItemAccessoryDO cateringOrderItemAccessoryDO = buildOrderItemAccDO(userContextHttpRequest, itemByItemId, accs, itemByOrderId.getId());
                        cateringOrderItemAccessoryMapper.produceOrder(cateringOrderItemAccessoryDO);
                    }
                }
                /*
                 * 子项 加料集合处理完成  判断子项加料是否全为出餐状态
                 */
                CateringOrderItemBO cateringOrderItemBO = cateringOrderQueryService.findItemByOrderId(orderId, item.getSeqNo(), userContextHttpRequest.getTenantId());
                if (cateringOrderItemBO.getAcc() != null) {
                    long count = cateringOrderItemBO.getAcc().stream().filter(itm -> "PREPARED".equals(String.valueOf(itm.getStatus()))).count();

                    if (count == (long) cateringOrderItemBO.getAcc().size()) {
                        /*
                         * 相等则 子项加料全部处理为出餐状态  从而更改子项状态
                         */
                        CateringOrderItemDO cateringOrderItemDO = buildOrderItemDO(userContextHttpRequest, item, cateringOrderItemBO, cater.getId());
                        cateringOrderItemMapper.produceOrder(cateringOrderItemDO);
                    } else {
                        /*
                         * 子集未处理完成  父集还是为制作中
                         */
                        CateringOrderItemDO cateringOrderItemDO = buildOrderItemDO(userContextHttpRequest, item, cateringOrderItemBO, cater.getId());
                        cateringOrderItemDO.setStatus(null);
                        cateringOrderItemMapper.produceOrder(cateringOrderItemDO);
                    }
                } else {
                    /*
                     * 没有加料 则判断子订单 数量是否符合从而改变状态
                     */
                    CateringOrderItemDO cateringOrderItemDO = buildOrderItemDO(userContextHttpRequest, item, cateringOrderItemBO, cater.getId());
                    cateringOrderItemMapper.produceOrder(cateringOrderItemDO);
                }
            }
        }
        /*
         * 订单子项处理完成  处理订单本身
         */
        CateringOrderBO caternow = cateringOrderQueryService.findById(userContextHttpRequest, orderId);
        long count = caternow.getCateringOrderItemBOList().stream().filter(itm -> "PREPARED".equals(String.valueOf(itm.getStatus()))).count();
        if (count == (long) caternow.getCateringOrderItemBOList().size()) {
            /*
             * 相等则 订单子项已经全部出餐 从而更改父订单状态
             */
           cateringOrderMapper.produceOrder(userContextHttpRequest.getTenantId(), orderId, request.getVersion());
        }
        return cateringOrderQueryService.findById(userContextHttpRequest, orderId);
    }

    /**
     * 订单结账
     *
     * @param userContextHttpRequest 头部信息 租户号 用户号
     * @param orderId 订单id
     * @param request 结账信息 请求体
     * @return CateringOrderBO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CateringOrderBO billOrder(UserContextHttpRequest userContextHttpRequest, Long orderId, BillCateringOrderHttpRequest request) {
        CateringOrderBO orderBO = cateringOrderQueryService.findById(userContextHttpRequest, orderId);
        if ("PREPARED".equals(String.valueOf(orderBO.getStatus()))) {
            CateringOrderDO cateringOrderDO = buildOrderDO(userContextHttpRequest, orderBO, request);
            Integer exist = cateringOrderMapper.billOrder(cateringOrderDO);
            if (exist > 0) {
                return cateringOrderQueryService.findById(userContextHttpRequest, orderId);
            }
            throw new IllegalArgumentException("结账失败");
        } else {
            throw new IllegalArgumentException("结账状态不为已出餐 无法结账");
        }
    }

    /**
     * 加退菜
     *
     * @param userContextHttpRequest s
     * @param orderId 订单id
     * @param request 加退菜请求体
     * @return CateringOrderBO
     */
    @Override
    public CateringOrderBO adjustOrder(UserContextHttpRequest userContextHttpRequest, Long orderId, AdjustCateringOrderHttpRequest request) {
        /*
         * 构建子订单 DO
         */
        for (AdjustCateringOrderHttpRequest.Item item : request.getItems()) {
            CateringOrderItemDO cateringOrderItemDO = buildAdjItem(userContextHttpRequest, item, orderId);
            /*
             * 判断是添加还是修改
             */
            if (cateringOrderItemDO.getProductId() != null) {
                /*
                 * 执行添加
                 */
                cateringOrderItemMapper.insert(cateringOrderItemDO);
            } else {
                /*
                 * 执行修改
                 */
                cateringOrderItemMapper.updateItem(cateringOrderItemDO);
            }
            /*
             * 子订单 修改 添加完毕 执行 加料逻辑
             */
            for (AdjustCateringOrderHttpRequest.Item.Accessory acc : item.getAccessories()) {

                CateringOrderItemAccessoryDO cateringOrderItemAccessoryDO = buildAdjItemAcc(userContextHttpRequest, acc, cateringOrderItemDO.getId(), cateringOrderItemDO.getProductId());
                if (acc.getProductAccessoryId() != null) {
                    /*
                     * 执行添加逻辑
                     */
                    cateringOrderItemAccessoryMapper.insert(cateringOrderItemAccessoryDO);
                } else {
                    /*
                     * 执行修改逻辑
                     */
                    cateringOrderItemAccessoryMapper.updateItemAcc(cateringOrderItemAccessoryDO);

                }
            }
        }
        /*
         *  修改主订单 状态为制作中
         */
        CateringOrderDO cateringOrderDO = buildOrderDO(userContextHttpRequest, orderId, request.getVersion());
        /*
         * 先遍历子订单是否全为已取消  如果为已取消则改变主订单为以取消
         * 否则该变为 制作中
         */
        CateringOrderBO byId = cateringOrderQueryService.findById(userContextHttpRequest, orderId);
        Long cancelledCAN = byId.getCateringOrderItemBOList().stream().filter(item -> String.valueOf(item.getStatus()).equals("CANCELLED")
        ).count();
        Long cancelledPRE = byId.getCateringOrderItemBOList().stream().filter(item -> String.valueOf(item.getStatus()).equals("PREPARING")
        ).count();
        /*
         * 如果子订单没有 制作中
         */
        if (Long.valueOf(byId.getCateringOrderItemBOList().size()).equals(cancelledCAN)) {
            /*
             * 改变主订单为 以取消
             */
            cateringOrderDO.setStatus("CANCELLED");
            cateringOrderMapper.makeOrder(cateringOrderDO);

        } else if (cancelledPRE > 0 && (String.valueOf(byId.getStatus()).equals("PREPARING"))) {
            /*
             * 不用更改直接返回
             */
            return cateringOrderQueryService.findById(userContextHttpRequest, orderId);

        } else if (cancelledPRE > 0 && (!String.valueOf(byId.getStatus()).equals("PREPARING"))) {
            cateringOrderDO.setStatus("PREPARING");
            cateringOrderMapper.makeOrder(cateringOrderDO);
        } else {
            /*
             * 既 不是以取消 也不是以制作
             */
            cateringOrderDO.setStatus("PREPARED");
            cateringOrderMapper.makeOrder(cateringOrderDO);
        }

        return cateringOrderQueryService.findById(userContextHttpRequest, orderId);
    }

    /**
     * 加退菜
     * 构建子订单DO
     */
    private CateringOrderItemDO buildAdjItem(UserContextHttpRequest userContextHttpRequest, AdjustCateringOrderHttpRequest.Item requstItem, Long orderId) {
        CateringOrderItemDO cateringOrderItemDO = new CateringOrderItemDO();

        /*
         * 判断是否有菜品 id
         */
        if (requstItem.getProductId() != null) {

            cateringOrderItemDO.setTenantId(userContextHttpRequest.getTenantId());

            cateringOrderItemDO.setVersion(1);
            cateringOrderItemDO.setOrderId(orderId);
            /*
             * 加退菜的状态全设置为制作中
             */
            cateringOrderItemDO.setStatus("PREPARING");

            cateringOrderItemDO.setProductMethodId(requstItem.getProductMethodId());
            /*
             * 设置数量
             */
            cateringOrderItemDO.setProduceQuantity(BigDecimal.ZERO);
            cateringOrderItemDO.setLatestQuantity(requstItem.getQuantityOnAdjustment());
            cateringOrderItemDO.setPlaceQuantity(requstItem.getQuantityOnAdjustment());
            cateringOrderItemDO.setSeqNo(requstItem.getSeqNo());

            UserContextThriftRequest userContextThriftRequest = new UserContextThriftRequest();
            userContextThriftRequest.setTenantId(userContextHttpRequest.getTenantId());
            userContextThriftRequest.setUserId(userContextHttpRequest.getUserId());
            ProductDetailRemoteResponse byIdResponse = productRemoteService.findById(userContextThriftRequest, String.valueOf(requstItem.getProductId()));
            /*
             * 设置商品基本信息信息
             */
            cateringOrderItemDO.setProductId(byIdResponse.id);
            cateringOrderItemDO.setProductNameOnPlace(byIdResponse.name);
            cateringOrderItemDO.setProductUnitPriceOnPlace(byIdResponse.unitPrice);
            cateringOrderItemDO.setProductUnitOfMeasureOnPlace(byIdResponse.unitOfMeasure);
            /*
             * 根据前端传入的方法id  从thrift中过滤出符合条件的列
             */
            for (ProductDetailRemoteResponse.MethodGroup methodGroup : byIdResponse.getMethodGroups()) {
                methodGroup.getOptions().stream().filter(itemf -> itemf.id.equals(requstItem.getProductMethodId()))
                        .peek(itemp -> {
                            cateringOrderItemDO.setProductMethodGroupNameOnPlace(methodGroup.name);
                            cateringOrderItemDO.setProductMethodNameOnPlace(itemp.name);
                            cateringOrderItemDO.setProductMethodId(itemp.id);
                        }).count();
            }
            return cateringOrderItemDO;
        }
        /*
         * 设置头信息
         */
        cateringOrderItemDO.setTenantId(userContextHttpRequest.getTenantId());
        cateringOrderItemDO.setOrderId(orderId);
        cateringOrderItemDO.setSeqNo(requstItem.getSeqNo());
        cateringOrderItemDO.setVersion(requstItem.getVersion());
        cateringOrderItemDO.setStatus("PREPARING");
        /*
         * 查询 当前已有订单数据
         */
        CateringOrderItemBO itemByOrderId = cateringOrderQueryService.findItemByOrderId(orderId, requstItem.getSeqNo(), userContextHttpRequest.getTenantId());

        if (requstItem.getQuantityOnAdjustment().compareTo(BigDecimal.ZERO) == -1) {

            if (itemByOrderId.getQuantity().getLatest().compareTo(requstItem.getQuantityOnAdjustment().multiply(new BigDecimal(-1))) == -1) {
                throw new IllegalArgumentException("退菜超过当前数量---");
            }
        }
        /*
         * 设置当前数量 
         */
        cateringOrderItemDO.setLatestQuantity(itemByOrderId.getQuantity().getLatest().add(requstItem.getQuantityOnAdjustment()));
        /*
         * 设置下单数量
         */
        cateringOrderItemDO.setPlaceQuantity(itemByOrderId.getQuantity().getOnPlace().add(requstItem.getQuantityOnAdjustment()));
        if ((itemByOrderId.getQuantity().getOnPlace().add(requstItem.getQuantityOnAdjustment())).compareTo(BigDecimal.ZERO) == 0) {
            /*
             * 退菜等于下单 等于当前   则设置为已取消
             */
            cateringOrderItemDO.setStatus("CANCELLED");
        } else if (cateringOrderItemDO.getPlaceQuantity().compareTo(itemByOrderId.getQuantity().getOnProduce()) == 0) {
            /*
             * 当加退菜后的下单数量==出餐数量  改变为以出餐
             */
            cateringOrderItemDO.setStatus("PREPARED");
        } else {
            cateringOrderItemDO.setStatus("PREPARING");
        }


        return cateringOrderItemDO;
    }

    /**
     * 加退菜
     * 构建子订单加退料DO
     */
    private CateringOrderItemAccessoryDO buildAdjItemAcc(UserContextHttpRequest userContextHttpRequest, AdjustCateringOrderHttpRequest.Item.Accessory requestAcc, Long orderItemId, Long productId) {
        CateringOrderItemAccessoryDO cateringOrderItemAccessoryDO = new CateringOrderItemAccessoryDO();

        if (requestAcc.getProductAccessoryId() != null) {
            /*
             * 新增加料
             */

            cateringOrderItemAccessoryDO.setSeqNo(requestAcc.getSeqNo());
            cateringOrderItemAccessoryDO.setTenantId(userContextHttpRequest.getTenantId());
            cateringOrderItemAccessoryDO.setVersion(1);
            cateringOrderItemAccessoryDO.setOrderItemId(orderItemId);
            /*
             * 新增加料 默认设置为制作中
             */
            cateringOrderItemAccessoryDO.setStatus("PREPARING");
            /*
             * 设置数量
             */
            cateringOrderItemAccessoryDO.setProduceQuantity(BigDecimal.ZERO);
            cateringOrderItemAccessoryDO.setLatestQuantity(requestAcc.getQuantityOnAdjustment());
            cateringOrderItemAccessoryDO.setPlaceQuantity(requestAcc.getQuantityOnAdjustment());
            /*
             * thrift 查询 商品信息
             */
            UserContextThriftRequest userContextThriftRequest = new UserContextThriftRequest();
            userContextThriftRequest.setTenantId(userContextHttpRequest.getTenantId());
            userContextThriftRequest.setUserId(userContextHttpRequest.getUserId());
            ProductDetailRemoteResponse byIdResponse = productRemoteService.findById(userContextThriftRequest, String.valueOf(productId));
            for (ProductDetailRemoteResponse.AccessoryGroup accessoryGroup : byIdResponse.accessoryGroups) {
                accessoryGroup.getOptions().stream().filter(itemf -> itemf.getId().equals(requestAcc.getProductAccessoryId()))
                        .peek(item -> {
                            cateringOrderItemAccessoryDO.setProductAccessoryGroupNameOnPlace(accessoryGroup.name);
                            cateringOrderItemAccessoryDO.setProductAccessoryNameOnPlace(item.name);
                            cateringOrderItemAccessoryDO.setProductAccessoryId(item.id);
                            cateringOrderItemAccessoryDO.setProductAccessoryUnitOfMeasureOnPlace(item.unitOfMeasure);
                            cateringOrderItemAccessoryDO.setProductAccessoryUnitPriceOnPlace(item.getUnitPrice());
                        }).count();
            }
            return cateringOrderItemAccessoryDO;

        } else {
            /*
             * 在原先数据上执行修改
             */
            cateringOrderItemAccessoryDO.setTenantId(userContextHttpRequest.getTenantId());
            cateringOrderItemAccessoryDO.setSeqNo(requestAcc.getSeqNo());
            cateringOrderItemAccessoryDO.setVersion(requestAcc.getVersion());
            cateringOrderItemAccessoryDO.setOrderItemId(orderItemId);
            /*
             * 调整数量
             */

            /*
             * 查询 当前已有订单数据
             */
            CateringOrderItemAccessoryBO itemAccByOrderItemId = cateringOrderQueryService.findItemAccByItemId(orderItemId, requestAcc.getSeqNo(), userContextHttpRequest.getTenantId());

            if (itemAccByOrderItemId.getQuantity().getLatest().compareTo(requestAcc.getQuantityOnAdjustment()) == -1) {
                throw new IllegalArgumentException("退菜超过当前数量---");
            }
            /*
             * 设置当前数量
             */
            cateringOrderItemAccessoryDO.setLatestQuantity(itemAccByOrderItemId.getQuantity().getLatest().add(requestAcc.getQuantityOnAdjustment()));
            /*
             * 设置下单数量
             */
            cateringOrderItemAccessoryDO.setPlaceQuantity(itemAccByOrderItemId.getQuantity().getOnPlace().add(requestAcc.getQuantityOnAdjustment()));
            if (itemAccByOrderItemId.getQuantity().getOnPlace().add(requestAcc.getQuantityOnAdjustment()).compareTo(BigDecimal.ZERO) == 0) {
                /*
                 * 退菜等于下单 等于当前   则设置为已取消
                 */
                cateringOrderItemAccessoryDO.setStatus("CANCELLED");
            } else if (cateringOrderItemAccessoryDO.getPlaceQuantity().compareTo(itemAccByOrderItemId.getQuantity().getOnProduce()) == 0) {
                /*
                 * 当加退菜后的下单数量==出餐数量  改变为以出餐
                 */
                cateringOrderItemAccessoryDO.setStatus("PREPARED");
            } else {

                cateringOrderItemAccessoryDO.setStatus("PREPARING");
            }


            return cateringOrderItemAccessoryDO;
        }

    }


    /**
     * 构建订单制作DO
     */
    private static CateringOrderDO buildOrderDO(UserContextHttpRequest userContextHttpRequest, Long id, Integer version) {
        CateringOrderDO cateringOrderDO = new CateringOrderDO();
        cateringOrderDO.setLastModifiedBy(userContextHttpRequest.getUserId());
        cateringOrderDO.setTenantId(userContextHttpRequest.getTenantId());
        cateringOrderDO.setLastModifiedAt(new Date());
        cateringOrderDO.setId(id);
        cateringOrderDO.setStatus("PREPARING");

        return cateringOrderDO;
    }

    /**
     * 构建订单 结账DO
     */
    private static CateringOrderDO buildOrderDO(UserContextHttpRequest userContextHttpRequest, CateringOrderBO orderBO, BillCateringOrderHttpRequest request) {
        CateringOrderDO cateringOrderDO = new CateringOrderDO();
        cateringOrderDO.setId(orderBO.getId());

        cateringOrderDO.setStatus("BILLED");
        cateringOrderDO.setVersion(request.getVersion());
        cateringOrderDO.setTenantId(userContextHttpRequest.getTenantId());
        cateringOrderDO.setBillingPaid(request.getPaid());
        cateringOrderDO.setBillingPaymentChannel(String.valueOf(request.getPaymentChannel()));
        cateringOrderDO.setBillingPromotion(request.getPromotion());

        cateringOrderDO.setLastModifiedAt(new Date());
        cateringOrderDO.setLastModifiedBy(userContextHttpRequest.getUserId());
        return cateringOrderDO;
    }

    /**
     * 构建订单本身 DO
     */

    private static CateringOrderDO buildOrderDO(UserContextHttpRequest userContextHttpRequest, PlaceCateringOrderHttpRequest request) {
        CateringOrderDO cateringOrderDO = new CateringOrderDO();
        cateringOrderDO.setTenantId(userContextHttpRequest.getTenantId());
        cateringOrderDO.setCreatedAt(new Date());
        cateringOrderDO.setCreatedBy(userContextHttpRequest.getUserId());

        /*
         * 默认设置已下单
         */
        cateringOrderDO.setStatus("PLACED");
        /*
         * 设置初始版本
         */
        cateringOrderDO.setVersion(1);
        cateringOrderDO.setComment(request.getComment());
        /*
         * 用餐人数 int转str
         */
        cateringOrderDO.setCustomerCount(String.valueOf(request.getCustomerCount()));
        cateringOrderDO.setShopBusinessNo(request.getShopBusinessNo());
        cateringOrderDO.setTableNo(request.getTableNo());
        cateringOrderDO.setTotalPrice(request.getTotalPrice());

        return cateringOrderDO;
    }

    /**
     * 构建thrift 请求
     */
    private static UserContextThriftRequest buildThriftUserContext(UserContextHttpRequest request) {
        UserContextThriftRequest userContextThriftRequest = new UserContextThriftRequest();
        userContextThriftRequest.setTenantId(request.getTenantId());
        userContextThriftRequest.setUserId(request.getUserId());
        return userContextThriftRequest;
    }

    /**
     * 构建订单子项基础DO
     */
    private CateringOrderItemDO buildOrderItemDO(UserContextThriftRequest userContextThriftRequest, PlaceCateringOrderHttpRequest.Item request, Long orderId) {
        CateringOrderItemDO cateringOrderItemDO = new CateringOrderItemDO();
        cateringOrderItemDO.setTenantId(userContextThriftRequest.getTenantId());

        cateringOrderItemDO.setVersion(1);
        cateringOrderItemDO.setOrderId(orderId);
        cateringOrderItemDO.setStatus("PLACED");

        cateringOrderItemDO.setProductMethodId(request.getProductMethodId());
        /*
         * 设置数量
         */
        cateringOrderItemDO.setProduceQuantity(BigDecimal.ZERO);
        cateringOrderItemDO.setLatestQuantity(request.getQuantity());
        cateringOrderItemDO.setPlaceQuantity(request.getQuantity());

        cateringOrderItemDO.setSeqNo(request.getSeqNo());
        ProductDetailRemoteResponse byIdResponse = productRemoteService.findById(userContextThriftRequest, String.valueOf(request.getProductId()));

        saveObj = byIdResponse;//保存 thrift的信息
        /*
         * 设置商品基本信息信息
         */
        cateringOrderItemDO.setProductId(byIdResponse.id);
        cateringOrderItemDO.setProductNameOnPlace(byIdResponse.name);
        cateringOrderItemDO.setProductUnitPriceOnPlace(byIdResponse.unitPrice);
        cateringOrderItemDO.setProductUnitOfMeasureOnPlace(byIdResponse.unitOfMeasure);
        /*
         * 根据前端传入的方法id  从thrift中过滤出符合条件的列
         */
        System.out.println(saveObj + "thrift获取到的数据");

        for (ProductDetailRemoteResponse.MethodGroup methodGroup : byIdResponse.getMethodGroups()) {
            methodGroup.getOptions().stream().filter(itemf -> itemf.id.equals(request.getProductMethodId()))
                    .peek(itemp -> {
                        cateringOrderItemDO.setProductMethodGroupNameOnPlace(methodGroup.name);
                        cateringOrderItemDO.setProductMethodNameOnPlace(itemp.name);
                        cateringOrderItemDO.setProductMethodId(itemp.id);
                    }).count();
        }
        return cateringOrderItemDO;
    }

    /**
     * 构建出餐所需要啊的子订单DO
     */
    private CateringOrderItemDO buildOrderItemDO(UserContextHttpRequest userContextHttpRequest, ProduceCateringOrderHttpRequest.Item item, CateringOrderItemBO itemBO, Long orderId) {
        CateringOrderItemDO cateringOrderItemDO = new CateringOrderItemDO();
        cateringOrderItemDO.setOrderId(orderId);
        cateringOrderItemDO.setSeqNo(item.getSeqNo());
        cateringOrderItemDO.setTenantId(userContextHttpRequest.getTenantId());
        /*
         * 如果出餐== 下单数量 则修改为以出餐状态
         */
        if (itemBO.getQuantity().getOnPlace().compareTo(item.getQuantityOnProduce().add(itemBO.getQuantity().getOnProduce())) == 0) {
            cateringOrderItemDO.setStatus("PREPARED");
        }
        /*
         * 当前数量
         */
        cateringOrderItemDO.setLatestQuantity(itemBO.getQuantity().getLatest().subtract(item.getQuantityOnProduce()));
        /*
         * 出餐数量
         */
        cateringOrderItemDO.setProduceQuantity(itemBO.getQuantity().getOnProduce().add(item.getQuantityOnProduce()));
        cateringOrderItemDO.setVersion(item.getVersion());

        return cateringOrderItemDO;
    }

    /**
     * 出餐时构建加料
     */
    private CateringOrderItemAccessoryDO buildOrderItemAccDO(UserContextHttpRequest userContextHttpRequest, CateringOrderItemAccessoryBO accessoryBO, ProduceCateringOrderHttpRequest.Item.Accessory request, Long orderItemId) {
        CateringOrderItemAccessoryDO accessoryDO = new CateringOrderItemAccessoryDO();
        if (accessoryBO.getQuantity().getOnPlace().compareTo(accessoryBO.getQuantity().getOnProduce().add(request.getQuantityOnProduce())) == 0) {
            accessoryDO.setStatus("PREPARED");
        }
        accessoryDO.setVersion(request.getVersion());
        accessoryDO.setSeqNo(request.getSeqNo());
        accessoryDO.setOrderItemId(orderItemId);
        accessoryDO.setTenantId(userContextHttpRequest.getTenantId());
        /*
         * 当前数量
         */
        accessoryDO.setLatestQuantity(accessoryBO.getQuantity().getLatest().subtract(request.getQuantityOnProduce()));
        /*
         * 出餐数量
         */
        accessoryDO.setProduceQuantity(accessoryBO.getQuantity().getOnProduce().add(request.getQuantityOnProduce()));
        return accessoryDO;
    }
    /**
     * 构建订单子项加料
     */
    private CateringOrderItemAccessoryDO buildOrderItemAccDO(UserContextThriftRequest userContextThriftRequest, PlaceCateringOrderHttpRequest.Item.Accessory request, Long orderItemId) {
        CateringOrderItemAccessoryDO cateringOrderItemAccessoryDO = new CateringOrderItemAccessoryDO();
        cateringOrderItemAccessoryDO.setSeqNo(request.getSeqNo());
        cateringOrderItemAccessoryDO.setTenantId(userContextThriftRequest.getTenantId());
        cateringOrderItemAccessoryDO.setVersion(1);
        cateringOrderItemAccessoryDO.setOrderItemId(orderItemId);
        cateringOrderItemAccessoryDO.setStatus("PLACED");
        /*
         * 设置数量
         */
        cateringOrderItemAccessoryDO.setProduceQuantity(BigDecimal.ZERO);
        cateringOrderItemAccessoryDO.setLatestQuantity(request.getQuantity());
        cateringOrderItemAccessoryDO.setPlaceQuantity(request.getQuantity());
        System.out.println(saveObj.accessoryGroups.get(0).options.get(2).getId().equals(request.getProductAccessoryId()));
        for (ProductDetailRemoteResponse.AccessoryGroup accessoryGroup : saveObj.accessoryGroups) {
            accessoryGroup.getOptions().stream().filter(itemf -> itemf.getId().equals(request.getProductAccessoryId()))
                    .peek(item -> {
                        cateringOrderItemAccessoryDO.setProductAccessoryGroupNameOnPlace(accessoryGroup.name);
                        cateringOrderItemAccessoryDO.setProductAccessoryNameOnPlace(item.name);
                        cateringOrderItemAccessoryDO.setProductAccessoryId(item.id);
                        cateringOrderItemAccessoryDO.setProductAccessoryUnitOfMeasureOnPlace(item.unitOfMeasure);
                        cateringOrderItemAccessoryDO.setProductAccessoryUnitPriceOnPlace(item.getUnitPrice());
                    }).count();
        }
        return cateringOrderItemAccessoryDO;
    }

}
